<?php
namespace Home\Controller;
use Think\Controller;

class OrderController extends CommonController {

    //订单列表
    public function index() {
        $state = I('get.state');
        $uid = session('user_id');
        $map['uid'] = $uid;

        switch($state){
            case "ncheck" ://审核
                $map2['a.uid'] = $uid;
                break;
            case "npay" : //待付款
                $map['is_pay'] = array('eq', -1);
                $map['status'] = array('neq', -1);
                break;
            case "is_d" ://待收货
                $map['is_deliver'] = 1;
                $map['status'] = array('neq' ,3);
                break;
            case "to_d" ://待发货
                $map['is_pay'] = array('eq', 1);
                $map['is_deliver'] = array('eq', -1);
                break;
            default : ;break;
        }

        //搜索(订单号)
        $search = trim(I('get.search'));
        if ( !empty($search) ) {
            ($state == 'ncheck') ? $map2['b.order_id'] = $search : $map['order_id'] = $search;
        }

        //订单列表
        if ($state == 'ncheck') {//审核
            $order = D('Admin/Order')->orderGoodThrough($map2,'0,3');

        } else {//全部,待付款,待发货,待收货
            $order = D('Admin/Order')->orderGood($map,'0,3');
        }
        foreach($order as $key =>$value){
            foreach ($value['order_good'] as $ley =>$val){
                $order[$key]['order_good'][$ley]['order_status'] = M('back_order')->where(array('order_id'=>$val['order_id'],'good_id'=>$val['good_id']))->getField('order_status');
                $order[$key]['order_good'][$ley]['spec_str'] = unserialize($order[$key]['order_good'][$ley]['spec_str']);
            }
        }
        //print_r($order);
        $this->assign('search', $search);
        $this->assign('state', $state);
        $this->assign('order', $order);
        $this->display();
    }

    // 查询订单的运费
    public function freight()
    {
        $good_ida = I('post.good_id');
        $freight_id = I('post.freight_id');
        $address_id = I('post.address_id');
        $good_num  = I('post.num');
//        $good_type = I('post.good_type');
        $good_idaarray = explode(",",$good_ida);
        $good_numarray = explode(",",$good_num);
//        $good_typearray = explode(",",$good_type);

        $agentAddress = M('agentAddress')->where( array('address_id'=>$address_id) )->find();
        $express_area_name = M('expressAreaname')->where( array('area_name'=>$agentAddress['city'],'express_id'=>$freight_id) )->find();
        if(!$express_area_name){
            $express_area_name = M('expressAreaname')->where( array('area_name'=>$agentAddress['province'],'express_id'=>$freight_id) )->find();
        }
        $express_area = M('express_area')->where( array('id'=>$express_area_name['express_area_id']) )->find();
        if(!$express_area){
            $this->ajaxReturn(-1);
        }
        $is_agent = M("agent")->where("agent_id = %d" ,array(session("user_id")))->getField("is_agent");
        foreach($good_idaarray as $key=>$value) {

            // 查询商品的重量
            $good = M('good')->where(array('id' => $value))->find();
            // 商品是否包邮
            if($good['is_free'] == 1){
//                包邮就没有重量了
                $weight = 0 ;
            }else{
                // 该商品的品牌下，该用户层级是否包邮
                $rank_id = M('agent_brand')->where(array('agent_id'=>session('user_id'),'brand_id'=>$good['brand_id']))->getField('rank_id');
                $is_free = M('agent_rank')->where(array('rank_id'=>$rank_id))->getField('is_free');
                if($is_free == 1){
                    $weight = 0 ;
                }else{
                    $num = $good_numarray[$key];
                    // 计算重量
                    $weight = $good['weight'] * $num;
                }
            }
            $sum[$key]=$weight;
        }
        $weight_sum = ceil(array_sum($sum));
        if($weight_sum<=$express_area['standard']&&!empty($weight_sum)){
            $fright_prices = $express_area['standard']*$express_area['down_num'];
        }elseif(empty($weight_sum)){
            $fright_prices = 0;
        }else{
            $up_fright = ($weight_sum - $express_area['standard'])*$express_area['up_num'];
            $down_fright = $express_area['standard']*$express_area['down_num'];
            $fright_prices = $up_fright + $down_fright;
        }
        $this->ajaxReturn($fright_prices);
    }

    //订单详情
    public function detail()
    {
        $order_model = new \Home\Model\OrderModel();
        $good_ida = I('post.good_ida');
        $good_num = I('post.good_num');
        $count = I('post.count');
        $status = I('post.status');
        $check_status = I("post.check_status");
        //购物车的商品id
        $good_aid = I('post.good_aid');
        $spec_str = I("post.good_spec");
        //筛选出已选的商品

        if(!empty($check_status)){
            foreach ($check_status as $ff =>$gg){
                if($gg == "-1"){
                    unset($good_ida[$ff]);
                    unset($good_num[$ff]);
                    unset($status[$ff]);
                    unset($good_aid[$ff]);
                    unset($spec_str[$ff]);
                }
            }
        }

        if(is_null($spec_str)){
            $spec_str = "";
        }

        //筛选后键名重新从0排序
         if(is_array($good_ida)){
            $good_ida = array_values($good_ida);
        }
        if(is_array($good_num)){
            $good_num = array_values($good_num);
        }
        if(is_array($status)){
            $status = array_values($status);
        }
        if(is_array($good_aid)){
            $good_aid = array_values($good_aid);
        }
        //商品id验证
        if(!is_array($good_ida)){
            $good_ida = explode(",",$good_ida);
        }
        //商品数量验证
        if(!is_array($good_num)){
            $good_num = explode(",",$good_num);
        }
        //验证商品状态(箱or件)
        if(!is_array($status)){
            $status = explode(",",$status);
        }
        //是数组下的一个商品(购物车过来的,立即购买的一个商品spec_str为字符串)
        if(is_array($spec_str)){
            $spec_str = array_values($spec_str);
            //是否一个商品
            if(count($good_ida) == 1){
                $spec_str = implode(",",$spec_str);
            }
        }

        //参数验证
        //if (IS_POST) {
        $single_good = $order_model->order_param_validate($good_ida,$status,$good_num,$spec_str);
        if(is_numeric($single_good)){
            $this->redirect($_SERVER['HTTP_REFERER']);
//                switch ($single_good){
//                    case -1:$this->error("商品信息有误",$_SERVER['HTTP_REFERER']);break;
//                    case -2:$this->error("商品状态信息有误",$_SERVER['HTTP_REFERER']);break;
//                    case -3:$this->error("商品数量至少为一件",$_SERVER['HTTP_REFERER']);break;
//                    case -4:$this->error("规格信息有误",$_SERVER['HTTP_REFERER']);break;
//                    case -5:$this->error("收货地址有误",$_SERVER['HTTP_REFERER']);break;
//                    case -6:$this->error("邮费信息有误",$_SERVER['HTTP_REFERER']);break;
//                    case -7:$this->error("总价合计有误",$_SERVER['HTTP_REFERER']);break;
//                }
        }
        //}

        //查询代理的层级
        $user_id = session('user_id');
        $agent = M('agent')->where( array('agent_id'=>$user_id) )->find();
        //可选快递
        $express = M('express')->where( array('state'=>1,'shop_id' =>session('reception_shopid')) )->order('id DESC')->select();

        $data = $order_model->order_sum_weight($good_ida,$good_num,$status,$good_aid,$spec_str,$single_good);

        if(array_sum($data['sum']) != $count){
            $this->error("数据有误",U("GoodShopcart/shopcart"));
        }

        //计算总件数
        $address = M("agent_address")->where("state = 0 AND agent_id = %d",array(session("user_id")))->select();
        $totalsum = array_sum($good_num);
        //print_r($goods);
        $this->assign('totalsum',$totalsum);
        $this->assign('address',$address);
        $this->assign('express', $express);
        $this->assign('agent', $agent);
        $this->assign('goods', $data['goods']);
        $this->assign('count',$count);
        $this->assign('good_num',implode(",",$good_num));
        $this->assign('good_ida',implode(",",$good_ida));
        $this->assign('status',implode(",",$status));
        $this->assign('good_aid',implode(",",$good_aid));
        if(count($good_ida) == 1){
            $ppap = array($spec_str);
            $this->assign("spec_str",base64_encode(serialize($ppap)));
        }else{
            $this->assign("spec_str",base64_encode(serialize($spec_str)));
        }
        $this->display();
    }

    //用户确认下单
    public function order_confirm()
    {
        //订单信息
        $id = I('get.id');
        $uid = session('user_id');
        $order = D('Admin/order')->relation(true)->where(array('id' => $id))->find();


        //订单里面的商品
        $orderGood = D('Admin/OrderGood')->relation(true)->where(array('order_id' => $order['id']))->select();
        $ordercount = D('Admin/OrderGood')->relation(true)->where(array('order_id' => $order['id']))->count();

        foreach($orderGood as $tey => $tal){
            //还原规格值
            $orderGood[$tey]['spec_str'] = unserialize($orderGood[$tey]['spec_str']);
            $good = M('good')->where(array('id'=>$tal['id']))->find();
            $new_rank_id = M('agentBrand')->where( array('brand_id'=>$good['brand_id'], 'agent_id'=>session('user_id')) )->getField('rank_id');
            $res = M('good_rank_price')->where(array('good_id' => $tal['id'], 'rank_id' => $new_rank_id))->find();
            $good_type = M('order_good')->where(array('good_id'=>$tal['id']))->getField('good_type');
            $orderGood[$tey]['unit_amt'] = $res['unit_amt'];
            $orderGood[$tey]['batch_amt'] = $res['batch_amt'];
        }

        $brand_name = M('brand')->where( array('id'=>$orderGood[0]['brand_id']) )->getField('b_name');
        //是否为董事
        $res = top_rank($orderGood[0]['brand_id']);
        if ($res['agent_id'] == $uid) {
            $this->assign('is_director', 1);
        }
        //预存款
        $brand_money = M('agent')->where( array('agent_id'=>$uid) )->getField('money');

        //查询是否有代理此品牌
        $brand = M('agent_brand')->where( array('agent_id'=>$uid, 'brand_id'=>$orderGood[0]['brand_id']) )->find();

        //查询下单人订单的总金额
        $orderThrough = M('orderThrough')->where( array('order_id'=>$id, 'uid'=>$uid) )->find();

        //查询上级代理应该付的订单的金额
        $sum = top_order_price($id, $uid);

        //如果是微信支付类(没有代理此品牌和平台商品的话)
        if (empty($brand) || $orderGood[0]['type'] == 2) {
            $this->assign('real_pay', 1);
        }
        // 配送方式
        $expres = M("express")->where("shop_id = %d" ,array(session('reception_shopid')))->field("e_name,id")->select();
        foreach ($expres as $ev) {
            $send_type[$ev["id"]] = $ev["e_name"];
        }
        // 支付方式
        $is_agent = M('agent')->where(array('agent_id'=>session('user_id')))->getField('is_agent');
        if($is_agent == 1){
            $pay_type = M("payment")->where("pay_code = 'balance'")->field("p_id,pay_code,p_name")->select();
        }else{
            $pay_type = D("PaymentView")->where("payment_conf.installed = 1")->field("p_id,pay_code,p_name")->select();
        }
        //查询发货人的姓名
        $agent_name = M('agent')->where( array('agent_id'=>$order['deliver_person']) )->getField('agent_name');
        // 收货人地址
        $address = M("agent_address")->where("address_id = %d" ,array($order['address_id']))->find();
        //拿退货状态码
        foreach($orderGood as $key =>$value){
            $orderGood[$key]['order_status'] = M('back_order')->where(array('order_id'=>$order['id'],'good_id'=>$value['good_id']))->getField('order_status');
        }
        $this->assign('is_agent',$is_agent);
        $this->assign('pay_type', $pay_type);
        $this->assign('send_type', $send_type);
        $this->assign('address', $address);
        $this->assign('sum', $sum);
        $this->assign('agent_name', $agent_name);
        $this->assign('orderThrough', $orderThrough);
        $this->assign('orderGood',$orderGood);
        $this->assign('order',$order);
        $this->assign('brand',$brand);
        $this->assign('brand_name',$brand_name);
        $this->assign('brand_money',$brand_money);
        $this->assign('uid',$uid);
        $this->assign('ordercount',$ordercount);
        $this->display();
    }

    //上级代理本人发货
    public function my_deliver() {
        //把订单的发货状态改为1和写入发货人
        $uid = session('user_id');
        $order_id = I('post.order_id');
        $price_sum = I('post.price_sum');
        $bool = M('order')->where( array('id'=>$order_id) )->save( array('is_deliver'=>1, 'deliver_person'=>$uid,'deliver_time' => time()) );
        //把订单流程表的state改为1
        M('orderThrough')->where( array('uid'=>$uid, 'order_id'=>$order_id) )->save( array('state'=>1, 'is_deliver'=>1, 'price'=>$price_sum) );
        //写入快递号
        $code_num = I('post.code_num');
        M('order')->where( array('id'=>$order_id) )->save( array('code_num'=>$code_num) );
        $this->ajaxReturn($bool);
    }

    //确认收货并返利
    public function confirm_good() {
        //把订单状态改为已完成
        $order_id = I('post.order_id');
        // 验证订单
        $order = M('order')->where("uid = %d AND id = %d" ,array(session("user_id") ,$order_id))->find();
        if($order["is_pay"] != 1 || $order["is_deliver"] != 1) {
            $this->ajaxReturn(array("status" => "error" ,"msg" => "订单信息有误"));
        }
        M('order')->where( array('id'=>$order_id) )->save( array('status'=>3) );

        //计算业绩
        $all_chi = M('agent')->where( array('agent_id'=>$order['uid']) )->getField('all_achi');
        $new_all_chi = $order['price'] + $all_chi;
        M('agent')->where( array('agent_id'=>$order['uid']) )->save( array('all_achi'=>$new_all_chi) );
        $this->ajaxReturn(array("status" => "success"));
    }

    //加载更多的商品
    public function more()
    {
        //过滤条件
        $num = (I('post.page') - 1)*3;
        $state = I('post.state');
        $uid = session('user_id');
        $map['uid'] = $uid;

        switch($state){
            case "ncheck" :
                $map2['a.uid'] = $uid;
                break;
            case "npay" :
                $map['is_pay'] = array('eq', -1);
                $map['status'] = array('neq', -1);
                break; // 待付款
            case "is_d" :
                $map['is_deliver'] = 1;
                $map['status'] = array('neq' ,3);
                break;// 已发货
            case "to_d" :
                $map['is_pay'] = 1;
                $map['is_deliver'] = -1;
                break; // 已支付
            default : ;break;
        }
        $search = trim(I('post.search'));
        if ( !empty($search) ) {
            ($state == 'ncheck') ? $map2['b.order_id'] = $search : $map['order_id'] = $search;
        }
        if ($state == 'ncheck') {//审核
            $order = D('Admin/Order')->orderGoodThrough($map2,"$num,3");
        } else {//全部,待付款,待发货,待收货
            $order = D('Admin/Order')->orderGood($map,"$num,3");
        }

        if (empty($order)) {
            echo 1;
        } else {
            $this->assign('order', $order);
            $this->display();
        }
    }

    //取消订单
    public function cancel()
    {
        //下单人和上级才能取消订单
        $uid_arr = array();
        $order_id = I('post.order_id');
        $uid = M('order')->where( array('id'=>$order_id) )->getField('uid');
        array_push($uid_arr,$uid);
        $through = M('orderThrough')->field('uid')->where( array('order_id'=>$order_id) )->select();
        foreach ($through as $v) {
            array_push($uid_arr,$v['uid']);
        }
        $uid = session('user_id');
        //取消订单
        if (in_array($uid, $uid_arr)) {
            $where["id"] = $order_id;
            $where["is_pay"] = -1;
            $bool = M('order')->where($where)->save( array('status' => -1) );
            //还原库存
            $order_good = M("order_good")->where(array("order_id"=>$order_id))->select();
            foreach($order_good as $key =>$value){
                //当商品为件的时候
                if($value['good_type'] == 2){
                    //先查出一箱是多少件
                    $per_num =  M("good")->where(array("id"=>$value["good_id"]))->getField("per_num");
                    M("good")->where(array("id"=>$value["good_id"]))->setInc("stock",$value['num']*$per_num);
                }else{
                    M("good")->where(array("id"=>$value["good_id"]))->setInc('stock',$value['num']);
                }
            }
            $this->ajaxReturn($bool);
        }
    }

    //提交订单
    public function place()
    {
        $order_model = new \Home\Model\OrderModel();
        //在order_model开启事务
        $order_model->startTrans();
        $shop_id = session('reception_shopid');
        $uid = session('user_id');
        $good_id = I('post.good_id');
        $message = I('post.message');
        $good_type = I('post.good_type');
        $number = I('post.num');
        //连运费的总价
        $price = I('post.price');
        //运费
        $freight_price = I('post.freight_price');
        $address_id = I('post.address_id');
        $send_type = to_int(I('post.send_type'));
        //规格
        $spec_str = I("post.spec_str");
        $spec_str = unserialize(base64_decode($spec_str));
        if(count($spec_str) == 1){
            $spec_str = implode(",",$spec_str);
        }
        //参数验证
        $single_good = $order_model->order_param_validate($good_id, $good_type, $number, $spec_str);
        //验证完之后再还原为传过来的数组
        if (is_numeric($single_good)) {
            $this->ajaxReturn($single_good);
        }
        if (!is_array($good_id)) {
            $good_id = explode(",", $good_id);
        }
        if (!is_array($number)) {
            $number = explode(",", $number);
        }
        if (!is_array($good_type)) {
            $good_type = explode(",", $good_type);
        }
        //检测是否普通商品与代理商品混在了一起
        $bool = $order_model->agent_or_normal($good_id);
        if($bool == false){
            $this->ajaxReturn(-9);
        }
        //先查询是否有收货地址，没有的话没法提交
        $agentAddress = M('agentAddress')->where(array('agent_id' => $uid))->find();
        if (empty($agentAddress)) {
            $this->ajaxReturn(-5);
        }
        $datb = $order_model->order_sum_weight($good_id, $number, $good_type, "", $spec_str, $single_good);
        $goods_count_amt = array_sum($datb['sum']);
        //计算出邮费价格
        $count_freight_price = $order_model->count_freight(array_sum($datb['weight_sum']), $send_type, $address_id);
        if (!$freight_price == $count_freight_price) {
            $this->ajaxReturn(-6);
        }
        // 计算出总价
        $allsum = $goods_count_amt + $freight_price;// 总费用
        //验证算出来的总价与上传的总价是否一致
        if ($allsum != $price) {
            $this->ajaxReturn(-7);
        }
        //获取收货地址
        $detail_address = M('agentAddress')->where(array('address_id' => to_int(I('post.address_id'))))->find();
        //下单人的手机号码
        $user_phone = M('agent')->where(array('agent_id' => $uid))->getField('mobile');
        //插入到订单表
        $data = array(
            'order_id' => get_order_id(),
            'uid' => $uid,
            'address_id' => to_int($address_id),
            'time' => time(),
            'message' => $message,
            'price' => $price,
            'user_phone' => $user_phone,
            'detail_area' => $detail_address['province'] . $detail_address['city'] . $detail_address['area'] . $detail_address['detail_address'],
            'consignee' => $detail_address['consignee'],
            'phone' => $detail_address['mobile'],
            'freight_price' => to_int($freight_price),
            'send_type' => $send_type,
            'shop_id' => $shop_id
        );
        $id = M('order')->add($data);
        $stock_data = $order_model->order_good_stock($good_id,$number,$good_type,$spec_str,$id,$single_good);
        if (empty($stock_data)){
            // 提交事务
            $order_model->commit();
        }else{
            // 事务回滚
            $order_model->rollback();
            $this->ajaxReturn($stock_data);
        }
        //删除购物车
        $good_aid = I('post.good_aid');
        $good_aidarray = explode(",", $good_aid);
        foreach ($good_aidarray as $ley => $vall) {
            M('shop_cart')->where(array('agent_id' => session('user_id'), 'cart_id' => $vall))->delete();
        }
        //删除完之后进行重新排序
        $pa = M("shop_cart")->where(array("agent_id"=>session("user_id")))->select();
        $i=0;
        foreach ($pa as $puck => $vine){
            M("shop_cart")->where(array("agent_id"=>session("user_id"),"id"=>$vine['id']))->setField("cart_id",$i);
            $i++;
        }
        //下单把订单推送上级(如果没有上级,把订单推送给订单对应的的商品的任意1个品牌的最顶级代理)
        $order_model->order_push($id,$good_id);
        $this->ajaxReturn($id);
    }

    //推送订单给上一级
    public function confirm()
    {
        //订单id和用户id
        $iid = I('post.iid');
        $uid = session('user_id');

        //推送给上一级需要扣自己的余额
        $order_price = top_order_price($iid, $uid);
        $money = M('agent')->where( array('agent_id'=>$uid) )->getField('money');
        $freight_price = M('order')->where( array('id'=>$iid) )->getField('freight_price');
        $flag = $money - $order_price - $freight_price;// 上级代理订单总价格=订单本身的总价格($order_price)+下单人的运费($freight_price)
        if ($flag < 0) {//余额不足，返回-1
            $this->ajaxReturn(-1);
        } else {//扣余额
            M('agent')->where( array('agent_id'=>$uid) )->save( array('money'=>$flag) );
        }
        //推送给上级的时候,把记录的state改为1,代表已经审核过了
        M('orderThrough')->where( array('order_id'=>$iid, 'uid'=>$uid) )->save( array('state' => 1) );
        //生成给上一级的订单审核
        $parent_id = M('agent')->where( array('agent_id'=>$uid) )->getField('parent_id');

        if ($parent_id == 0 ) {//没上一级(董事，或无上一级的非董事)
            M('order')->where( array('id'=>$iid) )->save( array('is_platform'=>1) );
        } else {//有上一级
            $data = array(
                'uid' => $parent_id,
                'state' => 0,
                'order_id' => $iid,
                'is_deliver' => 0,
                'price' => top_order_price($iid,$parent_id),//上级代理订单的金额(不包括运费和折扣)
            );
            //设置此代理订单的总价格
            M('orderThrough')->add($data);
        }


        /*        if (!_is_director()) {//非顶层代理推送到上级的时候,生成记录
                    $data = array(
                        'uid' => $parent_id,
                        'state' => 0,
                        'order_id' => $iid,
                        'is_deliver' => 0,
                        'price' => top_order_price($iid,$parent_id),//上级代理订单的金额(不包括运费和折扣)
                    );
                    //设置此代理订单的总价格
                    M('orderThrough')->add($data);
                } else {//当最顶级代理提交到平台的话，把is_platform改为1,代表需要平台发货
                    M('order')->where( array('id'=>$iid) )->save( array('is_platform'=>1) );
                }*/
        $this->ajaxReturn(1);//成功返回1
    }

    // 计算订单支付手续费[不在用]
    public function sum_pay_fee()
    {
        if(IS_AJAX){
            $pay_type = to_int(I("post.pay_type"));
            $pay_amt = to_int(I("post.pay_amt"));
            $pay_fee = M("payment")->where("p_id = %d",array($pay_type))->getField("p_fee");
            $amt = round(($pay_fee * $pay_amt) / 100 ,2);
            $this->ajaxReturn(array("amt" => $amt));
        }else{
            exit("error");
        }
    }

    //退款
    public function back_money(){
        if(IS_AJAX) {
            $order_id = trim(I("post.order_id"));
            if(!$order_id){
                $this->error("订单ID不可为空",$_SERVER['HTTP_REFERER']);
            }
            $reason = trim(I("post.reason"));
            if(!$reason){
                $this->error("退款原因不可为空",$_SERVER['HTTP_REFERER']);
            }
            $back_sum = to_int(I("post.back_sum"));
            $back_remark = trim(I("post.back_remark"));

            $good_id = to_int(I("post.good_ida"));
            if(!$good_id){
                $this->error("商品ID不可为空",$_SERVER['HTTP_REFERER']);
            }
            $num = to_int(I("post.num_a"));
            if(!$num){
                $this->error("数量不可为空",$_SERVER['HTTP_REFERER']);
            }
            $date['agent_id'] = session('user_id');
            $date['order_id'] = $order_id;
            $date['good_id'] = $good_id;
            $date['num'] = $num;
            $date['reason'] = $reason;
            $date['back_sum'] = $back_sum;
            $date['remark'] = $back_remark;
            $date['order_status'] = 1;
            $date['time'] = NOW_TIME;
            $date['shop_id'] = session('reception_shopid');
            $res = M("back_order")->where(array('order_id' => $order_id,'good_id'=>$good_id))->find();

            if(empty($res)){
                $img_arr = I("post.img_arr");
                //存凭证图
                if (!empty($img_arr)) {
                    foreach ($img_arr as $key => $value) {
                        $data['order_id'] = $order_id;
                        $data['good_id'] = $good_id;
                        $data['img'] = $value;
                        M('back_img')->add($data);
                    }
                }
                M("back_order")->add($date);
                //在添加退款单之后
                //查询这个订单有几个已经提出了退款，若是全部，则订单状态为取消
                $goods = M('order_good')->where(array('order_id'=>$order_id))->select();
                $k = 0;
                $y = 0;
                foreach ($goods as $gay =>$lay) {
                    $result = M('back_order')->where(array('good_id'=>$lay['good_id'],'order_id'=>$order_id))->find();
                    if($result && $result['num'] == $lay['num']){
                        $k++;
                    }
                    $y++;
                }
                // 相等 设置状态
                if($k == $y ){
                    M('order')->where(array('id'=>$order_id))->setField('status' ,2);
                }
            }else {
                //已存在此订单中此商品的退款申请
                $this->ajaxReturn(-1);
            }
            $this->ajaxReturn(1);
        }else{
            $order_id = to_int(I("get.order_id"));
            $good_id  = to_int(I("get.good_id"));
            $is_agent = M('agent')->where(array('agent_id'=>session('user_id')))->getField('is_agent');
            $good_msg = M('good')->where(array('id'=>$good_id))->find();
            $ret = M('order_good')->where(array('good_id'=>$good_id,'order_id'=>$order_id))->find();
            $back_money_num = $ret['num'];

            //是否是代理
            if($is_agent == '1'){
                $res = single_good_amt($good_msg);
                if($ret['good_type'] == '1'){
                    $back_money_price = $res['unit_amt'];
                }elseif($ret['good_type'] == '2'){
                    $back_money_price = $res['batch_amt'];
                }
            }else{
                $back_money_price = $good_msg['price'];
            }

            // 商品是否是非代理商品
            $agen_brand = is_agent_normal($good_id);
            if($agen_brand == 0){
                $back_money_price = $good_msg['price'];
            }
            $sum = $back_money_price*$back_money_num;
            $back_good['id']  = $good_id;
            $back_good['name'] = $good_msg['g_name'];
            $back_good['img'] = $good_msg['img'];
            $back_good['num'] = $back_money_num;
            $back_good['price'] = $back_money_price;
            $back_good['spec_str'] = unserialize($ret['spec_str']);

            $this->assign('good', $back_good);
            $this->assign('good_order_id', $good_id);
            $this->assign('good_sum', $sum);
            $this->display();
        }
    }

    //计算手续费
    public function pay_charge()
    {
        if(IS_AJAX){
            $pay_type = to_int(I("post.pay_type"));
            $order_id = to_int(I("post.order_id"));
            $price = M('order')->where(array('id'=>$order_id))->getField('price');
            $freight = M('order')->where(array('id'=>$order_id))->getField('freight');
            $money = $price - $freight;
            $pay_fee = M("payment_conf")->where("p_id = %d AND shop_id = %d",array($pay_type ,session('reception_shopid')))->getField("p_fee");
            $pay_amt = round(($pay_fee * $money) / 100 ,2);
            $this->ajaxReturn($pay_amt);
        }else{
            exit("error");
        }
    }

}